<template>
  <div class="form">
    <h2 class="title"></h2>
    <a-divider :style="{ color: '#000' }" />
    <a-form :model="form" :style="{ width: '680px' }">
      <a-form-item
        field="username"
        label="用户名称："
        style="margin-bottom: 40px"
      >
        <a-input
          v-model="form.username"
          placeholder="请输入家人用户名"
          style="width: 400px; background-color: #fff; border-radius: 10px"
        />
      </a-form-item>
      <a-form-item field="password" label="用户密码:" style="margin-bottom: 40px">
        <a-input
          v-model="form.password"
          placeholder="请输入家人用户密码"
          style="width: 400px; background-color: #fff; border-radius: 10px"
        />
      </a-form-item>
      <div class="btn" style="width: 600px">
        <a-button type="primary" class="confirm" @click="confirmFun">创建</a-button>
        <a-button type="dashed" class="cancel" @click="resetForm">重置</a-button>
      </div>
    </a-form>
    <a-divider :style="{ color: '#000' }" />
  </div>
</template>

<script>
import { Register } from '@/api/login';
import { useRouter } from 'vue-router'; // 引入 useRouter

export default {
  props: {
    teacherlist: { type: Array },
  },
  data() {
    return {
      form: {
        username: '',
        password: '',
        Bid: '',
      },
    };
  },
  setup() {
    const router = useRouter(); // 获取路由实例
    return { router };
  },
  methods: {
    // 获取科目
    getAccountList() {
      
    },
    // 跳转页面
    gotoa() {
      this.$router.go(0);
    },
    // 创建事件
    async confirmFun() {
      // 表单验证
      if (!this.form.username || !this.form.password) {
        this.$message.error('用户名和密码不能为空');
        return;
      }
      let userInfo = localStorage.getItem('userInfo');
      try {
        let userObject = JSON.parse(userInfo);
        const res = await Register(
          this.form.username,
          this.form.password,
          userObject.userbid
        );
        if (res.data.data === 1) {
          this.$message.success('注册成功');
          this.resetForm(); // 注册成功后调用重置表单方法
          this.router.push('/authority/user'); // 跳转到 /authority/user 页面
        } else {
          this.$message.error(res.message || '注册失败，请稍后重试');
        }
      } catch (error) {
        console.error('解析用户信息或注册请求出错:', error);
        this.$message.error('网络错误，请稍后重试');
      }
    },
    // 重置表单方法
    resetForm() {
      this.form = {
        username: '',
        password: '',
        Bid: '',
      };
    },
    // 取消创建事件
    cancelFun() {
      this.$emit('cancelfun', false);
    },
  },
};
</script>

<style scoped lang="less">
.form {
  background-color: white;
  position: absolute;
  top: 45%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 600px;
  height: 280px;
}
.title {
  margin-left: 50px;
}
.btn {
  margin-left: 250px;
  .cancel {
    margin-left: 20px;
  }
}
a-form-item {
  margin-bottom: 20px;
}
</style>